package controllers.commands
{
	import com.google.maps.InfoWindowOptions;
	import com.google.maps.LatLng;
	import com.google.maps.Map;
	import com.google.maps.MapMouseEvent;
	import com.google.maps.overlays.Marker;
	import com.google.maps.overlays.MarkerOptions;
	import com.google.maps.overlays.Polyline;
	import com.google.maps.overlays.PolylineOptions;
	import com.google.maps.styles.FillStyle;
	import com.google.maps.styles.StrokeStyle;
	
	import controllers.commands.base.ICommand;
	import controllers.managers.LocationQueryManager;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.StyleSheet;
	import flash.text.TextFormat;
	
	import model.context.TrackerContext;
	import model.filter.ProtocalFilter;
	import model.registry.ColorTable;
	
	import mx.core.UIComponent;
	
	import utils.DeviceParser;
	
	import view.MapCanvas;
	
	/**
	 * 绘制历史轨迹线
	 **/
	public class DrawHistoryTrackerCommand implements ICommand
	{
		[Bindable]
		private var currentPositionData:Object;
		private var locationManager:LocationQueryManager = null;
		private var positionLineArray:Array;
		private var positionArray:Array;
		private var polylineOptions:PolylineOptions 
					= new PolylineOptions({strokeStyle: new StrokeStyle({color: 0xFF0000,thickness: 2,alpha: 0.7})});
		private var map:Map;
//		private var marker:Marker;
		private var context:TrackerContext;					
		private var toolTipStr : String = "";
		private var totalPositionObject:Object;
		private var mapCanvas:MapCanvas = null;
		
		public function DrawHistoryTrackerCommand()
		{			
		}
		
		public function setContext(context:Object):void
		{
			this.context = TrackerContext(context);
			
			if(context != null && context.mapCanvas != null)
			{
				mapCanvas = context.mapCanvas;	
				map = mapCanvas.map;
			}
			
			totalPositionObject = this.context.totalPos;
			locationManager = new LocationQueryManager();
			locationManager.addEventListener(LocationQueryManager.EVENT_UPDATE, onLocationUpdateHandler);
		}		
		
		/**
		 * 执行方法
		 **/
		public function execute():void
		{
			if(Global.currentMapType == 1)
			{
				positionArray = totalPositionObject.map;
				
			}else 
			{
				positionArray = totalPositionObject.sat;
			}
			
			positionArray = positionArray.filter(ProtocalFilter.doFilterProtocal);
			
			if(mapCanvas != null)
			{			
				drawLocPolyLine();
			}
		}
		
		private function onRollOverPoluLine(e:MouseEvent):void
		{
			
			var trackerLine:DisplayObject = e.target as DisplayObject;
			
			var effectI:int = int(trackerLine.name.substr(1));
			var positionData:Object = positionArray[effectI];						
			if(positionData)
			{
				locationManager.query( positionData.latitude + "," + positionData.longitude);			
			}
			
			this.mapCanvas.toolTip = toolTipStr;
		}
		
		private function onRollOutPoluLine(e:MouseEvent):void
		{
			this.mapCanvas.toolTip = "";
		}
		
		/**
		 * 更新地址信息
		 **/ 
		private function onLocationUpdateHandler(evt:Event):void
		{
			if(currentPositionData != null)
			{
				var addresText : String = LocationQueryManager(evt.currentTarget).formattedAddress;
				var endLatLng:LatLng = new LatLng(currentPositionData.latitude,currentPositionData.longitude);
				
				var infoList : Array = currentPositionData.status_text;
				var infoParser : DeviceParser = new DeviceParser(currentPositionData);
				//准备备注信息
				toolTipStr  = "";
				toolTipStr += " 时间: "+Global.getTimeStrByTime(currentPositionData.dateline, true ) + " \n" ;
				toolTipStr += " 方向: "+infoParser.getDirection() + "\n" ;
				toolTipStr +=  " 时速: "+infoParser.getSpeed() + "KM/h\n" ;
				toolTipStr += " 经度: "+infoParser.getLng() + "\n" ;
				toolTipStr += " 纬度: "+infoParser.getLat() + "\n" ;
				toolTipStr += " 地址: " + addresText + " \n" ;
				
				var tempStr : String = "";
				if(infoList != null)
				{
					for (var ii:int=0;ii<infoList.length;ii++)
					{
						tempStr += infoList[ii] + " " ;
					}
					toolTipStr += " 状态: " + tempStr + "\n";
				}
				
				var opObj:Object = { 
					strokeStyle:new StrokeStyle({color: ColorTable.GREY}),
					fillStyle: new FillStyle({color: ColorTable.DARK_RED, alpha: 1}),
					radius: 12,
					hasShadow: true,
					label:"P"}
				
//				if( marker == null )
//				{
				var marker:Marker = new Marker(endLatLng, new MarkerOptions(opObj));   
				marker.addEventListener(MapMouseEvent.ROLL_OVER, onDisplayLocInfoByState);
				marker.addEventListener(MapMouseEvent.ROLL_OUT, function():void{ marker.closeInfoWindow(); });
				map.addOverlay(marker);
//				}
//				else
//				{
//					map.removeOverlay(marker);
//				}
			}
		}
		
		/**
		 * 根据状态显示相应的颜色
		 **/
		private function onDisplayLocInfoByState(evt:MapMouseEvent):void
		{
			var marker:Marker = evt.currentTarget as Marker;
			if ( marker != null )
			{
				var contentStr:String = "";
				
				var contentStyle:StyleSheet = new StyleSheet();
				contentStyle.setStyle("color", "#00CC00"); 
				
				var contentFormat:TextFormat = new TextFormat();
				contentFormat.size = 12;
				contentFormat.color = ColorTable.BLACK;
				marker.openInfoWindow(new InfoWindowOptions({ content:toolTipStr,
					hasShadow : false,
					hasTail : false,
					width : 250,
					hasCloseButton : true,
					tailAlign : InfoWindowOptions.ALIGN_LEFT,
					pointOffset : new Point(130,130),
					contentFormat : contentFormat}));
			}				
		}
		
		/**
		 * 绘制历史轨迹
		 **/
		private function drawLocPolyLine():void
		{
			var polyline:Polyline;
			
			if(positionLineArray)
			{
				while(positionLineArray.length > 0)
				{
					polyline = positionLineArray.pop() as Polyline;
					//通过线显示信息
					polyline.foreground.removeEventListener(MouseEvent.ROLL_OVER,onRollOverPoluLine);
					polyline.foreground.removeEventListener(MouseEvent.ROLL_OUT,onRollOutPoluLine);
					map.removeOverlay(polyline);
				}
//				if(marker)
//				{
//					map.removeOverlay(marker);
//				}
			}
			
			positionLineArray = [];
			
			var cData:Object;
			var oData:Object;
			var startLatLng:LatLng;
			var endLatLng:LatLng;
			for (var i:int = 0; i < positionArray.length ; i ++)
			{
				if(cData)
				{
					oData = cData;
				}
				
				cData = positionArray[i];
				
				if(oData)
				{
					startLatLng = new LatLng(oData.latitude,oData.longitude);
					endLatLng = new LatLng(cData.latitude,cData.longitude);
					polyline = new Polyline([startLatLng,endLatLng],polylineOptions);
					
					polyline.foreground.name = "p" + i;
					polyline.foreground.addEventListener(MouseEvent.ROLL_OVER,onRollOverPoluLine);
					polyline.foreground.addEventListener(MouseEvent.ROLL_OUT,onRollOutPoluLine);
					positionLineArray.push(polyline);
					map.addOverlay(polyline);
				}
				
			}
			
			if(endLatLng)
			{
				createLocalInfoTip(endLatLng);			
			}
		}
		
		/**
		 * 创建位置详细信息提示
		 **/ 
		private function createLocalInfoTip(endLatLng:LatLng):void
		{
			if(currentPositionData == null)
			{
				currentPositionData = {};
				currentPositionData.latitude = endLatLng.lat();
				currentPositionData.longitude = endLatLng.lng();
			}
			locationManager.query( endLatLng.lat() + "," + endLatLng.lng());
			var opObj:Object = { 
				strokeStyle:new StrokeStyle({color: ColorTable.GREY}),
				fillStyle: new FillStyle({color: ColorTable.DARK_RED, alpha: 1}),
				radius: 12,
				hasShadow: true,
				label:"P"}
//			if( marker == null )
//			{
			var marker:Marker = new Marker(endLatLng, new MarkerOptions(opObj));   
			
			marker.addEventListener(MapMouseEvent.ROLL_OVER, onDisplayLocInfoByState);
			marker.addEventListener(MapMouseEvent.ROLL_OUT, function():void{ marker.closeInfoWindow(); });
			map.addOverlay(marker);
//			}
			map.panTo(endLatLng);
		}
	}
}